﻿using CommServer.Common;
using CommServer.Forms;
using CommServer.Models;
using McsUtility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TomNet.Redis;

namespace CommServer
{
    public partial class FrmMain : Form
    {
        //private static readonly string NodesKey = "NodeServers";
        //private static readonly string CommConfigKey = "CommConfig";
        //private static readonly string ClientDataKey = "ClientData";
		
        private delegate void showMsg(string msg);
        private showMsg addMsgDelegate;

        private bool disMsg = true;
        private AppState appState = AppState.Stoped;

        private Server server = new Server();

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            Init();
        }

        #region 初始化

        private void Init()
        {
            cbShowMsg.Checked = disMsg;
            addMsgDelegate = new showMsg(AddMsg);
            RefreshConfig();
            InitServer();
        }

        private void InitData()
        {
            //redisClient.HashGet<>
        }

        private void InitServer()
        {
            try
            {
                SetAppState(AppState.Stoped);
                server.OnMessage += new EventHandler<MsgEventArgs>(Server_OnMessage);
            }
            catch (Exception ex)
            {
                SetAppState(AppState.Error);
                AddMsg(ex.Message);
            }
        }

        private void Server_OnMessage(object sender, MsgEventArgs e)
        {
            AddMsg(e.Message);
        }

		#endregion

		#region  private void RefreshConfig()

		private void RefreshConfig()
        {
            try
            {
                var config = new CommConfig { Ip = "0.0.0.0", Port = "9999" };

                txtIp.Text = config.Ip;
                txtPort.Text = config.Port;
            }
            catch (Exception ex)
            {
                AddMsg("[RefreshConfig] -> " + ex.Message);
            }
        }

		#endregion

		#region 即时信息框

		void AddMsg(string msg)
        {
            if (!disMsg) return;
            if (lbxMsg.InvokeRequired)
            {
                lbxMsg.Invoke(addMsgDelegate, msg);
            }
            else
            {
                if (lbxMsg.Items.Count > 100)
                {
                    lbxMsg.Items.RemoveAt(0);
                }
                lbxMsg.Items.Add(msg);
                lbxMsg.TopIndex = lbxMsg.Items.Count - (int)(lbxMsg.Height / lbxMsg.ItemHeight);
            }
        }

        private void lbxMsg_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 'c' || e.KeyChar == 'C')
            {
                lbxMsg.Items.Clear();
            }
        }

		#endregion

		#region private void btnNodes_Click(object sender, EventArgs e)

		private void btnNodes_Click(object sender, EventArgs e)
        {
            var win = new FrmNodes();
            var result = win.ShowDialog();
        }

		#endregion

		#region private void SetAppState(AppState state) 设置程序状态。

		/// <summary>
		/// 设置程序状态。
		/// </summary>
		/// <param name="state"></param>
		private void SetAppState(AppState state)
        {
            appState = state;
            btnStart.Enabled = (appState == AppState.Stoped);
            btnStop.Enabled = (appState == AppState.Started);
            txtIp.Enabled = (appState == AppState.Stoped);
            txtPort.Enabled = (appState == AppState.Stoped);
        }

		#endregion

		#region private void btnStart_Click(object sender, EventArgs e)

		private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                string ip = txtIp.Text.Trim();
                ushort port = ushort.Parse(txtPort.Text.Trim());
                server.LocalIp = ip;
                server.LocalPort = port;

				SetAppState(AppState.Starting);
                server.Start();
                if (server.IsStart)
                {
                    SetAppState(AppState.Started);
                }
                else
                {
                    SetAppState(AppState.Stoped);
                }
            }
            catch (Exception ex)
            {
                AddMsg(string.Format("$Server Start Error -> {0}", ex.Message));
            }
        }

		#endregion

		#region private void btnStop_Click(object sender, EventArgs e)

		private void btnStop_Click(object sender, EventArgs e)
        {
            SetAppState(AppState.Stoping);
            server.Stop();
            if (!server.IsStart)
            {
                SetAppState(AppState.Stoped);
            }
        }

		#endregion

		#region private void cbShowMsg_CheckedChanged(object sender, EventArgs e)

		private void cbShowMsg_CheckedChanged(object sender, EventArgs e)
        {
            disMsg = cbShowMsg.Checked;
        }

		#endregion
	}
}
